/*
 * @Author: 周海 zhouhaib@yonyou.com
 * @Date: 2022-12-15 11:50:15
 * @LastEditors: zhouhai zhouhaib@yonyou.com
 * @LastEditTime: 2025-04-10 15:17:33
 */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { addDictData, updateDictData,delDictData } from '@/api/system/dictData';
import BillCard from '@/components/BillCard';
import { useStore } from '@/store';
import { DictDataDomain } from '@/type.d/system';
import { Button, Col, Form, Input, InputNumber, Modal, Radio, Row, Select, Space } from 'antd';
import React, { useEffect, useState } from 'react'
// import './index.less';

interface DictDataCardProp {
    dictTypes: any[];
    statusOptions: any[];
    /**
     * 卡片数据 受控
     */
    cardData: DictDataDomain;
    /**
     * 卡片新增时的默认数据
     */
    newdata?: DictDataDomain;
    /**
     * 列表数据
     */
    tableListDataSource: DictDataDomain[];
    /**
     * 更新列表数据
     */
    setTableListDataSource: (data: DictDataDomain[]) => void;

    setIsedit?: (isedit: boolean) => void;

    isedit?: boolean;
    /**
     * 跳转到列表状态
     */
    onBack?: (e?: React.MouseEvent<HTMLElement>) => void;
}
const DictDataCard: React.FC<DictDataCardProp> = ((props: DictDataCardProp) => {
    const { dictTypes = [], statusOptions = [], cardData, newdata = {}, tableListDataSource, setTableListDataSource, setIsedit, isedit = false, onBack } = props;
    const { layoutStore, userStore } = useStore();
    const [selectdata, setSelectdata] = useState<DictDataDomain>(cardData);
    const [oldSelectdata, setOldSelectdata] = useState<DictDataDomain>({});//编辑状态临时保存选中的菜单树数据
    const [formRef] = Form.useForm<DictDataDomain>();

    const intCardData = (_cardData: DictDataDomain) => {
        setSelectdata(_cardData)
        setOldSelectdata(_cardData)
    }



    const addCardData = (_cardData: DictDataDomain) => {
        setSelectdata(_cardData)
        setOldSelectdata({ ...selectdata })
        setIsedit?.(true)
    }

    const editCardData = () => {
        setOldSelectdata({ ...selectdata })
        setIsedit?.(true)
    }

    const resetCardData = () => {
        setSelectdata({ ...oldSelectdata })
        setOldSelectdata({})
    }

    const onDelete = (dedata: DictDataDomain) => {
        if (dedata.dictCode) {
            layoutStore.OpenSpanning()
            delDictData(dedata.dictCode).then(() => {
                setSelectdata({})
                setOldSelectdata({})
                setTableListDataSource(tableListDataSource.filter((item) => {
                    return item.dictCode !== dedata.dictCode
                }))
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }

    }

    useEffect(() => {//从列表跳转到卡片，如果数据发生了变化，更新数据
        intCardData(cardData)
    }, [])


    useEffect(() => {
        formRef.resetFields()
        if (selectdata) {
            formRef?.setFieldsValue({ ...selectdata });
        } else {
            formRef?.setFieldsValue({});
        }
    }, [selectdata])

    /**
    * 表单字段配置
    */
    const cardItems: JSX.Element =
        <Row>
            <Col md={8} xl={6} hidden>
                <Form.Item name="dictCode" label="字典数据主键">
                    <Input disabled />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="dictSort" label="字典排序" rules={[{
                    required: true,
                    message: '此项为必填项',
                },]}>
                    <InputNumber />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="dictType" label="字典类型" rules={[{
                    required: true,
                    message: '此项为必填项',
                },]}>
                    <Select options={dictTypes} disabled/>
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="dictLabel" label="字典标签" rules={[{
                    required: true,
                    message: '此项为必填项',
                },]}>
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="dictValue" label="字典键值" rules={[{
                    required: true,
                    message: '此项为必填项',
                },]}>
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="status" label="启用状态">
                    <Radio.Group options={statusOptions} disabled />
                </Form.Item>
            </Col>
            <Col md={24} xl={24}>
                <Form.Item name="remark" label="备注">
                    <Input.TextArea />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="createBy" label="创建者">
                    <Input disabled />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="createTime" label="创建时间">
                    <Input disabled />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="updateBy" label="更新者">
                    <Input disabled />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="updateTime" label="更新时间">
                    <Input disabled />
                </Form.Item>
            </Col>
        </Row >;


    const cardbuttons = (
        <Space>
            <Button
                size='small'
                key="add"
                type="primary"
                onClick={() => {
                    addCardData({ ...newdata, pkFathercorp: selectdata?.pkCorp })
                }}
            >
                新增
            </Button>
            <Button
                size='small'
                key="edit"
                type="primary"
                disabled={selectdata?.dictCode ? false : true}
                onClick={() => {
                    editCardData()
                }}
            >
                修改
            </Button>
            <Button
                size='small'
                key="delete"
                type="primary"
                disabled={selectdata?.dictCode ? false : true}
                onClick={() => {
                    Modal.confirm({
                        okText: '确定',
                        cancelText: '取消',
                        title: '系统提示',
                        content: '确定要删除数据吗？',
                        type: 'warning',
                        onOk: () => {
                            onDelete(selectdata)
                        }
                    }
                    )

                }}
            >
                删除
            </Button>
        </Space>
    )

    const onSave = () => {
        formRef.validateFields().then(() => {
            const data: DictDataDomain = formRef.getFieldsValue?.() || {};
            if (!selectdata.dictCode) {//新增
                layoutStore.OpenSpanning()
                addDictData({ ...selectdata, ...data }).then((res) => {
                    intCardData(res.data)//更新卡片数据
                    tableListDataSource.push(res.data)
                    setTableListDataSource([...tableListDataSource])
                    setIsedit?.(false)
                }).finally(() => {
                    layoutStore.CloseSpanning()
                })
            } else {//更新
                layoutStore.OpenSpanning()
                updateDictData({ ...selectdata, ...data }).then((res) => {
                    intCardData(res.data)//更新卡片数据
                    setTableListDataSource(tableListDataSource.map((item) => {
                        if (item.dictCode === res.data.dictCode) {
                            return res.data
                        } else {
                            return item
                        }
                    }))
                    setIsedit?.(false)
                }).finally(() => {
                    layoutStore.CloseSpanning()
                })
            }
        })
    }


    const editbuttions = (
        <Space>
            <Button
                size='small'
                key="save"
                type="primary"
                onClick={() => {
                    onSave()
                }}
            >
                保存
            </Button>
            <Button
                size='small'
                key="cancel"
                type="primary"
                onClick={() => {
                    resetCardData()
                    setIsedit?.(false)
                }}
            >
                取消
            </Button>
        </Space>
    )

    return (
        <BillCard
            formid='dictCode'
            key={'DictTypeCard'}
            formRef={formRef}
            isedit={isedit}
            extraButton={isedit ? editbuttions : cardbuttons}
            onBack={onBack}
            title={'字典数据管理'}
            cardItem={cardItems}
        />
    )
})
export default DictDataCard;